package cn.bugstack.springframework.beans.factory.support;

import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.ConfigurableListableBeanFactory;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: 对注册bean接口的一些实现
 * @date 2022/8/2 09:05
 */
public class DefaultListableBeanFactory extends AbstractAutowireCableBeanFactory  implements BeanDefinitionRegistry, ConfigurableListableBeanFactory {

    /**
     * 实例化一个线程安全的map用来存放BeanDefinition
     */
    private Map<String,BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();



    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition definition) {
        beanDefinitionMap.put(beanName,definition);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws BeansException {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if(null == beanDefinition){
            throw new BeansException("no bean named "+beanName+"is defined");
        }
        return beanDefinition;
    }

    @Override
    public boolean containsBeanDefinition(String beanName) throws BeansException {
        return beanDefinitionMap.containsKey(beanName);
    }

    @Override
    public void preInstantiateStringletons() throws BeansException{
        for (String s : beanDefinitionMap.keySet()) {
            getBean(s);
        }
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> beanType)  {
        Map<String,T> result = new HashMap<>();
        beanDefinitionMap.forEach((beanName,beanDefinition)->{
            Class beanClass = beanDefinition.getBeanClass();
            // a是否是b的父类
            if(beanType.isAssignableFrom(beanClass)){
                try {
                    result.put(beanName,(T) getBean(beanName));
                } catch (BeansException e) {
                    e.printStackTrace();
                }
            }
        });
        return result;
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return beanDefinitionMap.keySet().toArray(new String[0]);
    }
}
